from .shoutcut_import import *
from werkzeug.utils import secure_filename
import os
from app.constant import ImageForm
from app.model.image_model import ImageModel
from uuid import uuid4

bp = V1BluePoint('image', __name__, url_prefix='')

ALLOWED_EXTENSIONS = ['jpg', 'png', 'jpeg']


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@bp.route('image', methods=['POST'])
@any_user_require
def post_image():
    """上传图片"""
    img = request.files['img']
    type = request.args.get('type', 'unknown')
    if not img or not allowed_file(img.filename):
        return error_json(ResponseCode.PARAMETER_ERROR, '图片格式错误')

    filename = type + '_' + str(uuid4()) + '.' + img.filename.rsplit('.', 1)[1]
    img.save(os.path.join('./images', filename))
    image_model = ImageModel(filename, ImageForm.FROM_LOCAL)
    sqla_db.session.add(image_model)
    sqla_db.session.commit()
    if not image_model.id:
        return error_json(ResponseCode.INTERNAL_SERVER_ERROR, '图片保存失败')
    return success_json({'url': filename, 'from': ImageForm.FROM_LOCAL, 'id': image_model.id})


@bp.route('image', methods=['GET'])
@any_user_require
def get_image():
    """获取图片列表"""
    images: ImageModel = ImageModel.query.all()
    return success_json(ImageModel.to_list(images, hidden=ImageModel.default_hidden))
